<template>
  <div class="supplier-reconciliation">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">🏭 供应商对账</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleGenerate">
              <el-icon><DocumentAdd /></el-icon>
              生成对账单
            </el-button>
            <el-button type="success" @click="handleBatchSettle">
              <el-icon><Wallet /></el-icon>
              批量结算
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="供应商">
          <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item label="对账周期">
          <el-date-picker
            v-model="searchForm.period"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结算状态">
          <el-select v-model="searchForm.settleStatus" placeholder="请选择状态" clearable>
            <el-option label="未结算" value="unsettled" />
            <el-option label="部分结算" value="partial" />
            <el-option label="已结算" value="settled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计概览 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-label">应付总额</div>
            <div class="stat-value payable">¥{{ totalPayable.toLocaleString() }}</div>
            <div class="stat-trend">本月应付款项</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-label">已付金额</div>
            <div class="stat-value paid">¥{{ totalPaid.toLocaleString() }}</div>
            <div class="stat-trend">本月已结算</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-label">未结金额</div>
            <div class="stat-value unpaid">¥{{ totalUnpaid.toLocaleString() }}</div>
            <div class="stat-trend">待结算款项</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="6">
          <div class="stat-card">
            <div class="stat-label">供应商数</div>
            <div class="stat-value">{{ supplierCount }}</div>
            <div class="stat-trend">合作供应商总数</div>
          </div>
        </el-col>
      </el-row>

      <!-- 批量操作 -->
      <div v-if="selectedRows.length > 0" class="batch-actions">
        <el-alert :title="`已选择 ${selectedRows.length} 项，合计: ¥${calculateSelectedTotal().toLocaleString()}`" type="info" :closable="false">
          <template #default>
            <div class="batch-buttons">
              <el-button size="small" type="success" @click="handleBatchSettle">批量结算</el-button>
              <el-button size="small" type="primary" @click="handleBatchConfirm">批量确认</el-button>
              <el-button size="small" type="warning" @click="handleBatchExport">批量导出</el-button>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 对账列表 -->
      <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="对账单号" width="150" />
        <el-table-column prop="supplierName" label="供应商名称" width="200" />
        <el-table-column prop="supplierCode" label="供应商编码" width="130" />
        <el-table-column prop="period" label="对账周期" width="180">
          <template #default="{ row }">
            {{ row.startDate }} 至 {{ row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseAmount" label="采购金额" width="130">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.purchaseAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="returnAmount" label="退货金额" width="120">
          <template #default="{ row }">
            <span style="color: #e6a23c;">¥{{ row.returnAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="应付金额" width="130">
          <template #default="{ row }">
            <span class="payable-amount">¥{{ row.totalAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已付金额" width="120">
          <template #default="{ row }">
            <span style="color: #67c23a;">¥{{ row.paidAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unpaidAmount" label="未付金额" width="120">
          <template #default="{ row }">
            <span style="color: #f56c6c;">¥{{ row.unpaidAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="settleStatus" label="结算状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getSettleStatusTag(row.settleStatus)">
              {{ getSettleStatusText(row.settleStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">查看明细</el-button>
            <el-button 
              v-if="row.unpaidAmount > 0" 
              link 
              type="success" 
              @click="handleSettle(row)"
            >
              结算付款
            </el-button>
            <el-button link type="warning" @click="handleAdjust(row)">调整</el-button>
            <el-button link type="info" @click="handleExport(row)">导出</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 生成对账单对话框 -->
    <el-dialog 
      v-model="generateDialogVisible" 
      title="生成供应商对账单"
      width="600px"
    >
      <el-form :model="generateForm" label-width="100px">
        <el-form-item label="选择供应商">
          <el-select 
            v-model="generateForm.supplierIds" 
            multiple 
            placeholder="请选择供应商"
            style="width: 100%"
          >
            <el-option label="全部供应商" value="all" />
            <el-option label="三星显示" value="1" />
            <el-option label="LG Display" value="2" />
            <el-option label="TSMC" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="对账周期">
          <el-date-picker
            v-model="generateForm.period"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="账期设置">
          <el-input-number v-model="generateForm.paymentDays" :min="0" :max="180" />
          <span style="margin-left: 10px;">天</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGenerateSubmit">生成</el-button>
      </template>
    </el-dialog>

    <!-- 结算付款对话框 -->
    <el-dialog 
      v-model="settleDialogVisible" 
      title="结算付款"
      width="700px"
    >
      <el-form :model="settleForm" label-width="110px">
        <el-form-item label="对账单号">
          <el-input v-model="settleForm.reconciliationId" disabled />
        </el-form-item>

        <el-form-item label="供应商">
          <el-input v-model="settleForm.supplierName" disabled />
        </el-form-item>

        <el-form-item label="应付金额">
          <span class="amount-highlight">¥{{ settleForm.totalAmount?.toLocaleString() }}</span>
        </el-form-item>

        <el-form-item label="已付金额">
          <span style="color: #67c23a; font-weight: bold;">¥{{ settleForm.paidAmount?.toLocaleString() }}</span>
        </el-form-item>

        <el-form-item label="未付金额">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ settleForm.unpaidAmount?.toLocaleString() }}</span>
        </el-form-item>

        <el-divider />

        <el-form-item label="本次付款金额">
          <el-input-number 
            v-model="settleForm.payAmount" 
            :min="0" 
            :max="settleForm.unpaidAmount"
            :precision="2"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="付款方式">
          <el-select v-model="settleForm.paymentMethod">
            <el-option label="银行转账" value="bank_transfer" />
            <el-option label="支票" value="check" />
            <el-option label="现金" value="cash" />
            <el-option label="承兑汇票" value="acceptance" />
          </el-select>
        </el-form-item>

        <el-form-item label="付款账户">
          <el-select v-model="settleForm.payAccount">
            <el-option label="公司账户1 (招商银行)" value="account1" />
            <el-option label="公司账户2 (工商银行)" value="account2" />
          </el-select>
        </el-form-item>

        <el-form-item label="付款日期">
          <el-date-picker
            v-model="settleForm.payDate"
            type="date"
            placeholder="选择付款日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="settleForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="settleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSettleSubmit">确认付款</el-button>
      </template>
    </el-dialog>

    <!-- 对账明细对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="供应商对账明细"
      width="1200px"
    >
      <el-tabs v-model="detailTab">
        <el-tab-pane label="采购明细" name="purchase">
          <el-table :data="detailData.purchase" border max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="orderNo" label="采购单号" width="150" />
            <el-table-column prop="productName" label="产品名称" width="200" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="{ row }">
                ¥{{ row.unitPrice.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="130">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="退货明细" name="return">
          <el-table :data="detailData.return" border max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="returnNo" label="退货单号" width="150" />
            <el-table-column prop="productName" label="产品名称" width="200" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="amount" label="退货金额" width="130">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="退货原因" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="付款记录" name="payment">
          <el-table :data="detailData.payment" border max-height="400">
            <el-table-column prop="date" label="付款日期" width="120" />
            <el-table-column prop="paymentNo" label="付款单号" width="150" />
            <el-table-column prop="amount" label="付款金额" width="130">
              <template #default="{ row }">
                ¥{{ row.amount.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="method" label="付款方式" width="120" />
            <el-table-column prop="status" label="状态" width="100" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentAdd, Wallet } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  supplierName: '',
  period: null,
  settleStatus: ''
})

// 选中的行
const selectedRows = ref([])

// 统计数据
const totalPayable = ref(2456789)
const totalPaid = ref(1856234)
const totalUnpaid = ref(600555)
const supplierCount = ref(28)

// 表格数据
const tableData = ref([
  {
    id: 'DZ-SUP-202401001',
    supplierName: '三星显示',
    supplierCode: 'SUP001',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    purchaseAmount: 856234,
    returnAmount: 12000,
    totalAmount: 844234,
    paidAmount: 844234,
    unpaidAmount: 0,
    settleStatus: 'settled'
  },
  {
    id: 'DZ-SUP-202401002',
    supplierName: 'LG Display',
    supplierCode: 'SUP002',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    purchaseAmount: 756234,
    returnAmount: 8500,
    totalAmount: 747734,
    paidAmount: 400000,
    unpaidAmount: 347734,
    settleStatus: 'partial'
  },
  {
    id: 'DZ-SUP-202401003',
    supplierName: 'TSMC',
    supplierCode: 'SUP003',
    startDate: '2024-01-01',
    endDate: '2024-01-31',
    purchaseAmount: 1256789,
    returnAmount: 0,
    totalAmount: 1256789,
    paidAmount: 0,
    unpaidAmount: 1256789,
    settleStatus: 'unsettled'
  }
])

// 对账明细数据
const detailTab = ref('purchase')
const detailData = reactive({
  purchase: [
    { date: '2024-01-05', orderNo: 'PO202401001', productName: 'OLED屏幕', quantity: 100, unitPrice: 800, amount: 80000, status: '已入库' },
    { date: '2024-01-15', orderNo: 'PO202401002', productName: 'A17芯片', quantity: 200, unitPrice: 1200, amount: 240000, status: '已入库' }
  ],
  return: [
    { date: '2024-01-20', returnNo: 'RT202401001', productName: 'OLED屏幕', quantity: 10, amount: 8000, reason: '质量问题' }
  ],
  payment: [
    { date: '2024-01-25', paymentNo: 'PAY202401001', amount: 400000, method: '银行转账', status: '已完成', remark: '首付款' }
  ]
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 3
})

// 对话框
const generateDialogVisible = ref(false)
const settleDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 表单
const generateForm = reactive({
  supplierIds: [],
  period: null,
  paymentDays: 30
})

const settleForm = reactive({
  reconciliationId: '',
  supplierName: '',
  totalAmount: 0,
  paidAmount: 0,
  unpaidAmount: 0,
  payAmount: 0,
  paymentMethod: '',
  payAccount: '',
  payDate: '',
  remark: ''
})

// 计算选中总额
const calculateSelectedTotal = () => {
  return selectedRows.value.reduce((sum, row) => sum + row.unpaidAmount, 0)
}

// 获取结算状态标签
const getSettleStatusTag = (status) => {
  const map = {
    unsettled: 'danger',
    partial: 'warning',
    settled: 'success'
  }
  return map[status] || 'info'
}

// 获取结算状态文本
const getSettleStatusText = (status) => {
  const map = {
    unsettled: '未结算',
    partial: '部分结算',
    settled: '已结算'
  }
  return map[status] || status
}

// 搜索
const handleSearch = () => {
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.supplierName = ''
  searchForm.period = null
  searchForm.settleStatus = ''
  handleSearch()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 生成对账单
const handleGenerate = () => {
  generateDialogVisible.value = true
}

const handleGenerateSubmit = () => {
  ElMessage.success('对账单生成成功')
  generateDialogVisible.value = false
}

// 结算付款
const handleSettle = (row) => {
  Object.assign(settleForm, {
    reconciliationId: row.id,
    supplierName: row.supplierName,
    totalAmount: row.totalAmount,
    paidAmount: row.paidAmount,
    unpaidAmount: row.unpaidAmount,
    payAmount: row.unpaidAmount
  })
  settleDialogVisible.value = true
}

const handleSettleSubmit = () => {
  ElMessage.success('付款成功')
  settleDialogVisible.value = false
  handleSearch()
}

// 查看明细
const handleViewDetail = (row) => {
  detailDialogVisible.value = true
}

// 调整
const handleAdjust = (row) => {
  ElMessage.info('调整功能')
}

// 导出
const handleExport = (row) => {
  ElMessage.success(`正在导出对账单 ${row.id}`)
}

// 批量操作
const handleBatchSettle = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要结算的对账单')
    return
  }
  ElMessage.success('批量结算功能')
}

const handleBatchConfirm = () => {
  ElMessage.success('批量确认成功')
}

const handleBatchExport = () => {
  ElMessage.success('批量导出成功')
}
</script>

<style scoped>
.supplier-reconciliation {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value.payable {
  color: #409eff;
}

.stat-value.paid {
  color: #67c23a;
}

.stat-value.unpaid {
  color: #f56c6c;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
}

.batch-actions {
  margin-bottom: 20px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.amount-text {
  color: #409eff;
  font-weight: bold;
}

.payable-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.amount-highlight {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

